package com.moyun.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.moyun.model.po.system.SysUserEntity;
import com.moyun.syssecurity.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * <h3>moyun-base</h3>
 * <p>Mybatisplus的自动填充功能</p>
 *
 * @author : ybx
 * @date : 2021-08-20 10:35:09
 **/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * @return void
     * @Author yangboxuan
     * @Description 自定义填充策略
     * @Date 2021/8/20 10:37
     * @Param [metaObject]
     **/
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        String loginUserId = getLoginUserId();
        // 这里采用的策略: 插入时 将DB中的  createTime 与 modifyTime  字段保持同步
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "modifyTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "creater", String.class, loginUserId);
        this.strictInsertFill(metaObject, "modifier", String.class, loginUserId);
    }

    /**
     * @return void
     * @Author yangboxuan
     * @Description 自定义更新策略
     * @Date 2021/8/20 10:38
     * @Param [metaObject]
     **/
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        String loginUserId = getLoginUserId();
        this.strictUpdateFill(metaObject, "modifyTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "modifier", String.class, loginUserId);

    }

    /**
     * @return java.lang.Integer
     * @Author yangboxuan
     * @Description 获取登录用户的唯一id
     * @Date 2021/8/20 15:23
     * @Param []
     **/
    private String getLoginUserId() {
        SysUserEntity loginUser = null;
        String id = null;
        try {
            loginUser = SecurityUtil.getLoginUser();
            id = loginUser.getId();
        } catch (Exception e) {
            log.error("对DB单表字段 creater和modifier字段进行填充时,获取当前登录用户对象报错.MyMetaObjectHandler中.填充为:anonymous",e);
            id = "anonymous";
        }
        return id;
    }


}
